﻿using FFMpegCore;
using FFMpegCore.Enums;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Windows.Media.Core;

namespace DNFImagePacks2Manager.Helpers
{
    public class BinkPlayHelper
    {
        public static async Task PlayWithBinkPlay(Page page, string bk2FilePath, bool loop = false)
        {
            try
            {
                string binkPlayPath = Path.Combine(AppContext.BaseDirectory, "BinTools", "binkplay.exe");

                if (!File.Exists(binkPlayPath))
                {
                    DialogHelper.ShowErrorMessage(page, $"错误：找不到 binkplay.exe。路径: {binkPlayPath}");
                    return;
                }

                if (!File.Exists(bk2FilePath))
                {
                    DialogHelper.ShowErrorMessage(page, $"错误：找不到 Bink 视频文件。路径: {bk2FilePath}");
                    return;
                }

                string arguments = $"\"{bk2FilePath}\"";

                if (loop)
                {
                    arguments += " /L";
                }

                var startInfo = new ProcessStartInfo
                {
                    FileName = binkPlayPath,
                    Arguments = arguments,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = false,
                    RedirectStandardError = false
                };

                using (var process = Process.Start(startInfo))
                {
                    if (process == null)
                    {
                        DialogHelper.ShowErrorMessage(page, "无法启动 binkplay.exe 进程。");
                        return;
                    }

                    await process.WaitForExitAsync();
                }
            }
            catch (Exception ex)
            {
                DialogHelper.ShowErrorMessage(page, $"调用 binkplay.exe 时发生异常: {ex.Message}");
            }
        }


        private static async void PlayWithFFMpeg(Page page, string filePath)
        {
            try
            {
                ContentDialog progressDialog = DialogHelper.CreateNormalDialog(page, "转换中", "正在将BK2转换为可播放视频，请稍候...");

                var progressTask = progressDialog.ShowAsync();

                string? mp4Path = await ConvertBK2ToMP4WithFFmpegCore(filePath);

                progressDialog.Hide();

                if (!string.IsNullOrEmpty(mp4Path) && File.Exists(mp4Path))
                {
                    MediaPlayerElement mediaPlayer = new MediaPlayerElement
                    {
                        AreTransportControlsEnabled = true,
                        AutoPlay = true,
                        Source = MediaSource.CreateFromUri(new Uri(mp4Path))
                    };

                    var player = mediaPlayer.MediaPlayer;
                    if (player != null)
                    {
                        player.Volume = 0;
                    }

                    var transportControls = mediaPlayer.TransportControls;
                    if (transportControls != null)
                    {
                        transportControls.IsCompact = true;
                        transportControls.IsZoomButtonVisible = false;
                        transportControls.IsZoomEnabled = false;
                        transportControls.IsVolumeButtonVisible = false;
                        transportControls.IsVolumeEnabled = false;
                    }

                    DialogHelper.ShowNormalDialog(page, $"预览: {Path.GetFileNameWithoutExtension(filePath)}", mediaPlayer);

                    try
                    {
                        File.Delete(mp4Path);
                    }
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    DialogHelper.ShowErrorMessage(page, "无法转换BK2文件，需要安装FFmpeg");
                }
            }
            catch (Exception ex)
            {
                DialogHelper.ShowErrorMessage(page, $"无法处理视频文件: {ex.Message}");
            }
        }

        private static async Task<string?> ConvertBK2ToMP4WithFFmpegCore(string bk2Path)
        {
            try
            {
                string tempDir = Path.GetTempPath();
                string mp4Path = Path.Combine(tempDir, $"bk2_video_{Guid.NewGuid():N}.mp4");
                await FFMpegArguments
                    .FromFileInput(bk2Path)
                    .OutputToFile(mp4Path, true, options => options
                        .WithVideoCodec(VideoCodec.LibX264)
                        .WithAudioCodec(AudioCodec.Aac))
                    .ProcessAsynchronously();

                if (File.Exists(mp4Path) && new FileInfo(mp4Path).Length > 0)
                {
                    return mp4Path;
                }
            }
            catch (Exception)
            {
            }
            return null;
        }
    }
}
